package com.bicon.botu.mall.goods.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.toolkit.StringUtils;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import com.bicon.botu.mall.goods.commons.GoodsConstants;
import com.bicon.botu.mall.goods.dto.OrderCommentParam;
import com.bicon.botu.mall.goods.dto.ProductCommentParam;
import com.bicon.botu.mall.goods.entity.ProductComment;
import com.bicon.botu.mall.goods.mapper.ProductCommentMapper;
import com.bicon.botu.mall.goods.service.IProductCommentService;
import com.bicon.botu.mall.order.rpc.service.OrderGoodsRpcService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  订单商品评价服务实现类
 * </p>
 *
 * @author liushujie
 * @since 2018-05-29
 */
@Slf4j
@Service
public class ProductCommentServiceImpl extends ServiceImpl<ProductCommentMapper, ProductComment> implements IProductCommentService {

    @Autowired
    RedisHandler redisHandler;

    @Autowired
    ProductCommentMapper productCommentMapper;

    @Autowired
    private OrderGoodsRpcService orderGoodsRpc;

    /**
     * SY0013-08-新增评论—移动端
     * 客户端新增商品评论
     * 评论成功 需要更新订单状态（当订单中的所有商品都完成了 修改订单状态为已评价）
     * @param orderCommentParam 订单商品评论对象
     * @return true 成功、false失败
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean insert(OrderCommentParam orderCommentParam) {
        log.info("【******客户端商品评价，新增商品评价开始******】");
        List<ProductComment> productCommentList = new ArrayList<>();
        //redis 获取用户对象 userId
        String value = redisHandler.getGlobalRedisTemplate().getStringValue(GoodsConstants.BOTU_USER_USERINFO, orderCommentParam.getUserId());
        JSONObject jsonObject = JSONObject.parseObject(value);
        if(!StringUtils.checkValNotNull(jsonObject)){
            //用户获取失败
            log.info("【******客户端商品评价，新增商品评价，获取用户对象失败******】，userId："+orderCommentParam.getUserId());
            return false;
        }
        List<String> orderChildIds = new ArrayList<>();
        for(ProductCommentParam productCommentParam :orderCommentParam.getProductCommentParamList()){
            ProductComment productComment = new ProductComment();
            productComment.preInsert();
            productComment.setBuyingTime(orderCommentParam.getBuyingTime());
            productComment.setTenantId(orderCommentParam.getTenantId());
            productComment.setUserId(orderCommentParam.getUserId());
            productComment.setIsAnonymity(orderCommentParam.getIsAnonymity());
            //用户头像 昵称填充
            if (StringUtils.checkValNotNull(jsonObject)) {
                if (StringUtils.checkValNotNull(jsonObject.get("nickName"))) {
                    productComment.setUserName(jsonObject.getString("nickName"));
                } else {
                    productComment.setUserName(jsonObject.getString("name"));
                }
                if (StringUtils.checkValNotNull(jsonObject.get("smallImg"))) {
                    productComment.setUserAvatar(jsonObject.getString("smallImg"));
                }
            }
            //子商品id
            orderChildIds.add(productCommentParam.getId());
            productComment.setOrderId(orderCommentParam.getOrderId());
            productComment.setOrderNo(orderCommentParam.getOrderNo());
            productComment.setProductId(productCommentParam.getProductId());
            productComment.setProductType(productCommentParam.getProductType());
            productComment.setProductName(productCommentParam.getProductName());
            productComment.setSkuName(productCommentParam.getSkuName());
            productComment.setSkuUrl(productCommentParam.getSkuUrl());
            productComment.setLevel(productCommentParam.getLevel());
            productComment.setContent(productCommentParam.getContent());
            productComment.setIsPictures(productCommentParam.getIsPictures());
            productComment.setPicturesUrl(productCommentParam.getPicturesUrl());
            productComment.setProductServiceLevel(productCommentParam.getProductServiceLevel());
            productComment.setLogisticsServiceLevel(productCommentParam.getLogisticsServiceLevel());
            productComment.setCustomerServiceLevel(productCommentParam.getCustomerServiceLevel());
            productCommentList.add(productComment);
        }
        boolean flag = this.insertBatch(productCommentList);
        log.info("【******客户端商品评价，新增商品评价结束******】,评价结果："+flag);

        //如果评价成功 ，修改订单状态
        if(flag){
            //调用订单rpc接口
            //1、修改订单中子商品状态，为已评价
            //2、检查订单下的商品是否都评价了，如果都评价了，则修改订单状态
          BaseResult result =   orderGoodsRpc.updateEvaluateState(orderCommentParam.getOrderId(),orderChildIds);
          log.info("【******客户端商品评价，修改订单状态******】,结果："+JSONUtils.toJSONString(result));
        }
        return flag;
    }

}
